<template>
  <div>
    <searchBox @handleSearch="handleSearch" @handleReset="handleReset">
      <el-form :inline="true" :model="searchFrom.param" label-width="auto" label-position="left" ref="siteManageRef">
        <el-form-item label="网站名称" prop="name">
          <el-input placeholder="请输入" v-model.trim="searchFrom.param.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="域名" prop="domainName">
          <el-input placeholder="请输入" v-model.trim="searchFrom.param.domainName" clearable></el-input>
        </el-form-item>

        <el-form-item label="国家" prop="newCountryId">
          <el-tree-select v-model="searchFrom.param.newCountryId" :data="sys_country" style="width: 185px"
            :props="defaultProps" clearable />
        </el-form-item>
        <el-form-item label="货币" prop="currencyId">
          <el-select v-model="searchFrom.param.currencyId" placeholder="请选择" style="width: 192px" clearable>
            <el-option v-for="dict in sys_currency_code" :key="dict.id" :label="dict.description"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语言" prop="languageId">
          <el-select v-model="searchFrom.param.languageId" placeholder="请选择" style="width: 192px" clearable>
            <el-option v-for="dict in sys_language_type" :key="dict.id" :label="dict.description"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站点类型" prop="websiteTypeId">
          <el-select v-model="searchFrom.param.websiteTypeId" placeholder="请选择" style="width: 185px" clearable>
            <el-option v-for="dict in sys_site_type" :key="dict.id" :label="dict.name" :value="dict.id"
              :disabled="!dict.status"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前状态" prop="status">
          <el-select v-model="searchFrom.param.status" placeholder="请选择" style="width: 192px" clearable>
            <el-option v-for="dict in sys_site_status" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </searchBox>
    <div class="mb8" style="display: flex;justify-content: space-between;">
      <el-button type="primary" @click="choseIncident({}, 0)">新增</el-button>
      <el-button type="primary" @click="sitePublish">发布模板</el-button>
    </div>

    <el-table :data="tableData" style="height: calc(100vh - 380px)" v-loading="loading">
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="code" label="网站编号" width="200" />
      <el-table-column prop="name" label="网站名称" />
      <el-table-column prop="port" label="端口" width="100" align="center" />
      <el-table-column prop="domainName" label="域名" width="200" />
      <el-table-column label="国家" prop="countryName" width="100" />
      <el-table-column label="支持货币" width="200">
        <template #default="scope">
          <el-space spacer=" " wrap>
            <el-tag size="small" v-for="(item, index) in scope.row.newCurrencyCodes" :key="index"
              :type="index === 0 ? 'primary' : 'info'">{{ item }}</el-tag>
          </el-space>
        </template>
      </el-table-column>

      <el-table-column label="支持语言" width="200">
        <template #default="scope">
          <el-space spacer=" " wrap>
            <el-tag size="small" v-for="(item, index) in scope.row.newLanguageNames" :key="index"
              :type="index === 0 ? 'primary' : 'info'">{{ item }}</el-tag>
          </el-space>
        </template>
      </el-table-column>

      <el-table-column prop="websiteTypeName" label="站点类型" align="center" />
      <el-table-column label="当前状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt @change="switchProcess(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="newLastModified" label="更新时间" align="center" width="200" />
      <el-table-column prop="newPublishStatus" label="发布状态" align="center" width="200">
        <template #default="scope">
          <el-text class="mx-1" :type="scope.row.newPublishStatus?.elTagClass">{{ scope.row.newPublishStatus?.label
          }}</el-text>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-space spacer=" ">
            <el-button link type="primary" @click="choseIncident(scope.row, 0)">编辑</el-button>
            <el-button link type="primary" @click="choseIncident(scope.row, 1)">发布</el-button>
            <el-dropdown @command="(command) => commandHandler(scope.row, command)">
              <span class="el-dropdown-link">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="item in incidentList" :key="item.id" :command="item">
                    <el-text :type="item.type">{{ item.title }}</el-text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :limit="searchFrom.pageSize" :page="searchFrom.pageNum"
      @pagination="handleCurrentChange">
    </Pagination>
    <ReleaseDrawer :assemble="false" :isRelease="true" :publicFrom="publicItem" :releaseVisible="releaseVisible"
      @handleClose="handleReleaseClose" @handleSure="handleReleaseSure"></ReleaseDrawer>
    <ReleaseLog :logTableVisible="logTableVisible" :publicFrom="publicItem" @handleLogClose="handleLogClose">
    </ReleaseLog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import ReleaseDrawer from "./components/releaseDrawer.vue";
import ReleaseLog from "./components/releaseLog.vue";

const { proxy } = getCurrentInstance();
const { sys_publish_status } = proxy.useDict("sys_publish_status");
const router = useRouter();
const switchLoading = ref(true);
const loading = ref(true);
const searchFrom = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    websiteTypeId: null, //站点类别（站点类型）
    name: "", //网站名称
    domainName: "", //域名
    languageId: "", //语言id
    countryId: "", //区域id(国家)
    newCountryId: '',//新建国家--字段前端自定义
    currencyId: "", //货币id
    status: null, //状态
  },
}); //搜索参数
const publicItem = ref({}); //公共赋值数据
const sys_language_type = ref([]); //语言
const sys_currency_code = ref([]); //货币
const sys_country = ref([]); //国家
const sys_site_type = ref([]); //站点类型
const releaseVisible = ref(false); //默认不显示发布
const logTableVisible = ref(false); //默认不显示发布

const total = ref(0);
const tableData = ref([]);
onMounted(() => {
  getList();
  getSelectList();
});
const getList = () => {
  site.general
    .sitewebsiteList({
      data: searchFrom.value,
    })
    .then((res) => {
      loading.value=false;
      switchLoading.value = false;
      total.value = res.total;
      if (res.data?.length) {
        res.data = res.data.map((code) => {
          return {
            ...code,
            newCurrencyCodes: publicSorting(code.currencyCode, code.currencyCodes),//支持货币
            newLanguageNames: publicSorting(code.languageName, code.languageNames),//支持货币
            newPublishStatus: sys_publish_status.value.find(
              (e) => e.value === code.publishStatus
            ),
            newLastModified: proxy.DateTime(code.lastModified),
          };
        });
      }
      tableData.value = res.data;
      console.log(tableData.value);
    });
};

const choseIncident = (row, index) => {
  publicItem.value = row;
  if (index === 1) {
    router.push({ path: `sitePublish/publishSite`, query: { id: row.id } });
  } else {
    router.push({ path: `siteEdit`, query: { id: row.id } });
  }
};
const commandHandler = (row, command) => {
  publicItem.value = row;
  if (command.id === 2) {
    router.push({ path: `webManage`, query: { id: row.id, languageId: row.languageId } });
  } else if (command.id === 3) {
    router.push({ path: `siteProductSort`, query: { id: row.id, languageId: row.languageId } });
  } else if (command.id === 4) {
    router.push({ path: `siteProductList`, query: { id: row.id, languageId: row.languageId } });
  } else if (command.id === 5) {
    let newIds = [];
    newIds.push(row.id);
    getDeleteId(newIds);
  } else if (command.id === 6) {
    router.push({ path: `siteTagManage`, query: { id: row.id, languageId: row.languageId } });
  } else if (command.id === 7) {
    logTableVisible.value = true;
  }
  else if (command.id === 8) {
    updateRemote(row)//更新信息
  }
};
const sitePublish = () => {
  router.push({ path: `sitePublish/publishDisposition` });
}
const getSelectList = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {},
  };
  // 语言
  product.language.languageList().then((res) => {
    sys_language_type.value = res.data;
  });
  // 获取货币
  product.currency.currencyList().then((res) => {
    sys_currency_code.value = res.data;
  });
  // 站点类型
  site.general
    .sitewebsitetypeList({
      data: from,
    })
    .then((res) => {
      sys_site_type.value = res.data;
    });

  getCountry(from);
};
const getCountry = (from) => {
  site.country
    .countryList({
      data: from,
    })
    .then((res) => {
      res.data = addLevelToTree(res.data)
      sys_country.value = res.data;
    });
};
const addLevelToTree = (tree, parentLevel = 0) => {
  return tree.map((item) => ({
    ...item,
    newId: `${item.id}-${parentLevel + 1}`,
    children: item.children
      ? addLevelToTree(item.children, parentLevel + 1)
      : undefined,
  })
  )
}

const switchProcess = (rowItem) => {
  if (switchLoading.value) return;
  proxy.$modal
    .confirm("是否确认修改此数据类型？")
    .then(() => {
      site.general
        .sitewebsiteUpdatestatus({
          pathParams: {
            id: rowItem.id,
          },
          params: {
            status: rowItem.status,
          },
        })
        .then((res) => {
          if (res.code === 200) {
            getList();
            proxy.$modal.msgSuccess(res.message);
          }
        });
    })
    .catch((err) => {
      if (rowItem.status) {
        return (rowItem.status = 0);
      } else {
        return (rowItem.status = 1);
      }
    });
};
// 搜索
const handleSearch = () => {
  let newCountry = searchFrom.value.param.newCountryId
  const newMatch = newCountry.match(/([-+]\d*\.?\d+)/);
  searchFrom.value.param.countryId = newCountry.slice(0, newMatch.index);
  getList();
};
// 重置
const handleReset = () => {
  proxy.resetForm("siteManageRef");
  getList();
};
// 删除
const getDeleteId = (newArray) => {
  proxy.$modal.confirm("是否确认删除此数据类型？").then(() => {
    site.general
      .sitewebsiteRemovebatchbyids({
        data: {
          ids: newArray,
        },
      })
      .then((res) => {
        if (res.code === 200) {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        }
      });
  });
};
const updateRemote = (row) => {
  site.general.sitewebsiteUpdateremotewebsite(
    {
      pathParams: {
        id: row.id
      }
    }
  ).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(res.message);
    }

  })
}

// 分页
const handleCurrentChange = (newPage) => {
  searchFrom.value.pageNum = newPage.page;
  searchFrom.value.pageSize = newPage.limit;
  getList();
};
var defaultProps = reactive({
  children: "children",
  label: "description",
  value: "newId", // 指定 id 作为 value 属性
});
const publicSorting = (code, List) => {
  return List.sort((a, b) => (a === code ? -1 : b === code ? 1 : 0));
}
//取消发布
const handleReleaseClose = () => {
  releaseVisible.value = false;
};
// 确定
const handleReleaseSure = () => {
  releaseVisible.value = false;
  getList();

};
// 确定
const handleLogClose = () => {
  logTableVisible.value = false;
};
const incidentList = reactive([
  {
    title: "页面管理",
    type: "primary",
    id: 6,
  },
  {
    title: "网页管理",
    type: "primary",
    id: 2,
  },
  {
    title: "商品分类",
    type: "primary",
    id: 3,
  },
  {
    title: "站点商品",
    type: "primary",
    id: 4,
  },
  {
    title: "发布记录",
    type: "primary",
    id: 7,
  },
  {
    title: "更新信息",
    type: "primary",
    id: 8,
  },
  {
    title: "删除",
    type: "danger",
    id: 5,
  },
]);
const sys_site_status = ref([
  {
    name: "启用",
    id: 1,
  },
  {
    name: "停用",
    id: 0,
  },
]); //站点状态
</script>
